package contrl

import (
	"core/utils"
	"fmt"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type (
	Error struct {
		StatusCode int
		ErrCode    int
		ErrInfo    string
	}

	Response struct {
		Data    interface{} `json:"data"`
		ErrCode int         `json:"err_code"`
		ErrInfo string      `json:"err_info"`
	}

	Sign struct {
		Uid       int64
		ExpiredAt time.Time
	}
)

func GenError(err error) (e Error) {
	utils.StackLog(err.Error())
	e = Error{
		StatusCode: 200,
		ErrCode:    50000,
		ErrInfo:    err.Error(),
	}
	return
}

func GenErrorCode(code int, msg string) (e Error) {
	utils.StackLog(msg)
	e = Error{
		StatusCode: 200,
		ErrCode:    code,
		ErrInfo:    msg,
	}
	return
}

func GenErrorMsg(msg string) (e Error) {
	utils.StackLog(msg)
	e = Error{
		StatusCode: 200,
		ErrCode:    40002,
		ErrInfo:    msg,
	}
	return
}

func GetInt(c *gin.Context, key string) (out int) {
	out, _ = strconv.Atoi(c.GetString(key))
	return
}
func GetString(c *gin.Context, key string) (out string) {
	return c.GetString(key)
}

func GetInt64(c *gin.Context, key string) (out int64) {
	out, _ = strconv.ParseInt(c.GetString(key), 10, 64)
	return
}

func GetFloat64(c *gin.Context, key string) (out float64) {
	out, _ = strconv.ParseFloat(c.GetString(key), 64)
	return
}

func GetBool(c *gin.Context, key string) (out bool) {
	out, _ = strconv.ParseBool(c.GetString(key))
	return
}

func GetTime(c *gin.Context, key string) time.Time {
	unixTime := GetInt64(c, key)
	if unixTime > 10000000000 {
		unixTime /= 1000
	}
	if unixTime == 0 {
		return time.Time{}
	}
	return time.Unix(unixTime, 0)
}

func GetSlice(c *gin.Context, key string) (values []string) {
	values = make([]string, 0)
	i := 0
	for {
		v, exist := c.Request.Form[fmt.Sprintf("%s[%d]", key, i)]
		if !exist {
			break
		}
		values = append(values, v[0])
		i++
	}
	return
}

func GetSign(c *gin.Context) (sign *Sign) {
	sign = new(Sign)
	value, exists := c.Get("_sign")
	if !exists {
		return
	}
	sign, _ = value.(*Sign)
	return
}
